﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;
using System.Runtime.Serialization;
using Passwords.ViewModels;

namespace Passwords.Models
{
    [DataContract]
    public class Entity : INotifyPropertyChanged
    {
        private bool isModified;

        [IgnoreDataMember]
        internal DataViewModel ViewModel;

        [IgnoreDataMember]
        internal Entity Parent;

        [IgnoreDataMember]
        public bool IsModified
        {
            get { return isModified; }
            set
            {
                isModified = value;
            }
        }

        internal protected void OnPropertyChanged(string propertyName)
        {
            Entity parent = Parent;
            if (parent != null)
            {
                parent.OnChildChanged(this);
            }

            PropertyChangedEventHandler eh = PropertyChanged;
            if (null != eh)
            {
                IsModified = true;
                eh(this, new PropertyChangedEventArgs(propertyName));
            }
        }

        protected void OnChildChanged(Entity child)
        {
            var eh = ChildChanged;
            if (eh != null)
            {
                eh(child, EventArgs.Empty);
            }
            if (!IsModified)
            {
                IsModified = true;
                OnPropertyChanged("IsModified");
            }
        }

        public event PropertyChangedEventHandler PropertyChanged;

        /// <summary>
        /// Occurs when the property of a child has changed.
        /// </summary>
        public event EventHandler ChildChanged;
    }
}
